<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2">
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://imgcache.qq.com/qcloud/tcbjs/1.3.5/tcb.js"></script>
  <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  <script>
    const AppID = 'wxb0bbb77bb501cf0b'
    const EnvID = 'weapp-ebfl5'
    const app = tcb.init({
      env: EnvID // 环境id
    })
    window.onload = async (e) => {
      const auth = app.auth();
      // 6.9
      async function login() {
        // 1. 建议登录前先判断当前是否已经登录
        let loginState = await auth.getLoginState();
        if (!loginState) {
          // 2. 调用微信登录API
          // snsapi_base、snsapi_userinfo
          const provider = auth.weixinAuthProvider({
            appid: AppID, // 微信公众号的Appid
            scope: "snsapi_userinfo"
          })
          // signInWithRedirect方法不存在
          await provider.signIn();
          // {isAnonymous: false, credential: {accessToken,refreshToken}}
          loginState = await auth.getLoginState();
        }
        return loginState
      }
      let loginState = await login();
      console.log('loginState', loginState);
      let accessToken = loginState.credential.accessToken

      // 从库中取出用户信息，可使用帐号信息登录
      // 6.9 实现signIn登录，拿到loginState对象，并打印出来
      const db = app.database();
      if (loginState) {
        const res = await db.collection("user").where({
          nickName: "程序员LIYI"
        }).limit(1).get();
        if (res.data.length) {
          let user = res.data[0]
          auth.currentUser = user
          console.log('user', user);
        }
      }
      const user = auth.currentUser;
      console.log('user', user);

      // 6.10 测试实时数据监听
      const watcher = db.collection('message')
        .orderBy('_id', 'desc')
        .limit(10)
        .where({
          room: '100000'
        })
        .watch({
          onChange: function (snapshot) {
            if (snapshot.docs.length) {
              let doc = snapshot.docs[0]
              console.log('doc', doc);
            }
            // console.log('docs\'s changed events', snapshot.docChanges)
            // console.log('query result snapshot after the event', snapshot.docs)
            // console.log('is init data', snapshot.type === 'init')
          },
          onError: function (err) {
            console.error('the watch closed because of error', err)
          }
        })

      await db.collection('message').add({
        data: {
          room: '100000',
          user: 'web',
          text: 'message' + Math.random() * 1000
        }
      })

      // 6.11 获取临时链接，在web页面中展示图片
      const fileID = 'cloud://weapp-ebfl5.7765-weapp-ebfl5-1301675402/img.png'
      let fileRes = await app
        .getTempFileURL({
          fileList: [fileID]
        })
      let url = fileRes.fileList[0].tempFileURL
      console.log('url',url);
      $('#img1').attr('src', url)

    }
  </script>
</head>

<body>
  Hello Cloudbase
  <img id="img1" />
</body>

</html>